{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ 2621,  1264,  1264,  1264,  1264, 16636, 16636, 16636, 16636,\n",
       "         14378, 14378, 14378, 14378, 19760, 19760, 19760, 21908, 21908,\n",
       "         21908, 21908, 21908, 13366, 13366, 13366, 13366,   448,   448,\n",
       "           448, 22883, 22883, 22883, 22883, 29429, 29429, 29429, 24660,\n",
       "         24660, 24660, 24660, 31500, 31500,  8616,  8881,  8881,  3118,\n",
       "          3118,  3118,  2160,  2160,  2160, 17274, 17274, 17274, 17274,\n",
       "         28792, 28792, 28792, 28792, 28792, 28792, 28713, 28713, 28713,\n",
       "         28713, 28713, 28713,  4153,  4153,  4153,  4153, 23355, 23355],\n",
       "        [ 9986,  3404,  3111,  3111,  3111,  8273,  8273,  8273, 21183,\n",
       "         21183, 21183, 28782, 28782,  7649,  7649,  7649,  7649, 23993,\n",
       "         23993,  1843,  1843,  5667,  5667,  5667,  5667,  5667,  5667,\n",
       "          5667, 13397, 13397,  5667, 13397, 13397, 13397, 13397, 13397,\n",
       "         21492, 21492, 21492,  2193,  9981,  9981,  9981,  9981,  9981,\n",
       "          9981,  9981, 26799, 27094, 27094,  5556,  5556,  5556,  5556,\n",
       "          5556, 29429, 29429, 29429, 29429, 25948, 25948,  9419, 20635,\n",
       "         10751, 10751, 10751, 10751, 10751, 10751, 23070,  8088, 26614],\n",
       "        [ 4860,  4860,  4255,  4255,  4255,  7899, 29686, 29686, 29686,\n",
       "         29686, 21008, 21008, 21008, 16002, 16002, 16002, 16002,  6665,\n",
       "          6665,  6665,  6665,  6665,  6665, 22162, 22100, 22100,  7722,\n",
       "          7722,  7722,  1678,  1678, 16839, 16839,  7476,  7476,  7476,\n",
       "          7476, 18819, 18819, 18819, 18106, 18106, 18106, 18106, 18106,\n",
       "          2917,  2917, 31932, 31932, 27238, 10883,  9603, 10753, 10753,\n",
       "         10753, 23251, 18450, 18450, 25404, 16475, 16475, 16277, 21834,\n",
       "         21834, 21834, 21834, 30948, 19357, 14917, 14917, 14917, 18421],\n",
       "        [24829, 24829, 26984, 18819, 18819, 18819, 30718, 30718, 16618,\n",
       "         16618, 16618, 26208, 26208, 26208,   364, 23624, 23624, 23624,\n",
       "         23624, 23624, 21052, 21052, 12045, 12045, 12045, 12045, 12045,\n",
       "          1843,  1843,  1843,  1843,  1843,  8852,  8852,  4420,  4420,\n",
       "          4420,  4420,  1497, 21999, 21999, 16622,  3856,  3856,  3856,\n",
       "          3856,  1707, 29823, 29823, 20269, 20269, 20269, 25760, 25760,\n",
       "         25760, 25760,   807,   807, 10013, 10013, 11858, 11858, 11858,\n",
       "         11858, 11858, 11858, 11858, 30044, 30044, 30044, 30044, 30044],\n",
       "        [ 1403,  4829,  4829,  4829,  4829, 20663, 20663, 19101, 20663,\n",
       "          7416,  7416,  7416, 11801, 11801, 18380, 17518, 11581, 18858,\n",
       "         18858, 11581, 18858, 18858, 18858, 10224, 10224, 10224, 10224,\n",
       "         10224,  6184,  6184,  6184, 19654, 24538, 24538, 24538, 24538,\n",
       "          2007,  2007,  2007,  2007, 17342,  5407, 16018, 16018,  4015,\n",
       "          4015,  4015,  4015,  4015,  5677,   982,   982, 30588,  5043,\n",
       "          5043,  5043,  5043,  5043,  5043,  5043,  5043,  5043, 11627,\n",
       "         11627, 11903, 11903, 11903, 11903, 11903, 11903, 11903, 11903],\n",
       "        [ 8771,  8771,  8771,  8771,  8771,  8771,  8771, 17624, 17624,\n",
       "         16176, 16176, 16176, 16176,  6804,  6804, 25034, 25034, 25034,\n",
       "         25034,  6884, 30518, 30518, 30518, 30518, 28688, 28688, 17660,\n",
       "          9333,  9333, 30083, 30083, 30083, 15811, 15811,  9295,  9295,\n",
       "         22614, 29182, 29182, 29182, 29182, 29182, 29182,  3842,  3842,\n",
       "          3842, 15502, 15502, 22015, 22015, 15502, 22015, 22015,  8208,\n",
       "          8208, 31583, 31583, 27460, 27460, 31583, 31583,  4636,  4636,\n",
       "          4636,  4636,  4636, 12851, 15119, 19792, 19792, 19792, 19792],\n",
       "        [20026, 20026, 20026, 20026, 24192, 24192, 24192, 20899, 20899,\n",
       "         20899,  8732, 30671, 30671, 26461, 26461, 26461, 26461,  6542,\n",
       "          6542,  6542,  6542, 26257, 26257, 26257, 12980, 12980, 12980,\n",
       "         12980, 12980, 12980, 10886, 10886, 10886, 10886, 10886, 26756,\n",
       "         26756, 11327, 11327, 11327, 11327, 11327, 11327,  2178,  2178,\n",
       "         11327,  2178,  2178,  2178,  1264,  1264,  1264,  1264,  1264,\n",
       "          1264, 15627, 15627, 15627, 15627, 23802, 23802, 23802, 23802,\n",
       "         23802, 23802, 23802,  3077,  3077,  1722,  7633,  3375,  3375],\n",
       "        [22197, 22197, 16953, 16953, 16953, 16953, 15268, 26173, 26173,\n",
       "         26173, 30909, 30909,  8516,  8516,  8516, 25629, 23270, 23270,\n",
       "         23270, 23270, 25128, 22140, 22140, 21079, 21079, 21079, 21079,\n",
       "         21079, 12334, 12334, 12334, 12334, 12334, 21129, 21129, 21129,\n",
       "         21129, 21129, 11611,  1531,  1531,  1531,  1531,  1531,  1531,\n",
       "          1531,  1531, 17501, 17501, 27061, 27061, 17709, 17709,  5029,\n",
       "          5029,  5029,  5029,  5029, 11777, 21666, 21666, 21666, 21666,\n",
       "          1115,  1115,  1115,  1115,  1115, 15186, 15186, 21959, 21959],\n",
       "        [11646, 15335, 16834,  4607,  4607,  4607,  4607,   846,   846,\n",
       "           846, 24604, 27544, 27544, 27544, 27544,  4774,  4774,  4774,\n",
       "          4774,  9576,  9576,  9576,  9576,  9576, 30742, 30742, 30742,\n",
       "         30742, 30557, 30557, 30557, 21078, 21586, 21586, 27571, 21586,\n",
       "         27571, 27571, 23894, 23894, 19990, 19990, 19990, 19990,  4633,\n",
       "          4633,  4633,  4633, 16593, 16593, 12997, 12997, 12997, 12997,\n",
       "         21271, 21271, 21271, 21271, 14570, 31072, 31072, 31072, 13971,\n",
       "         13971, 11326, 11326, 11326, 11326, 11326, 11326, 11326, 11326],\n",
       "        [ 6765,  3061, 22218, 22218,  6391,  6391,  6391, 23610, 23610,\n",
       "         23610, 23610,   141,   141,   141,   141,   141,   141,   141,\n",
       "           141, 10857, 10857, 10857,   141, 28050, 28050, 28050, 28050,\n",
       "         28050, 29592, 29592, 24009, 31800, 31800, 23303, 23303, 12114,\n",
       "         12114, 12114, 12114, 30874, 30874, 12114, 30874, 30874, 30874,\n",
       "         30874, 30874, 30874, 30874, 24383, 24383, 24383, 21404, 21404,\n",
       "         21404,  6237,  6237,  6237, 21404,  2497, 19717,  2497, 19717,\n",
       "         25832, 25832, 25832,  2254,  2254,  2254,  2254,  2254,  1680]],\n",
       "       dtype=int32), 10.373835, 0.0]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.336, cost=4.07]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.88it/s, accuracy=0.344, cost=3.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.263012, training avg acc 0.226258\n",
      "epoch 1, testing avg loss 3.926299, testing avg acc 0.355242\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.465, cost=2.98]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.468, cost=2.76]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.384498, training avg acc 0.420094\n",
      "epoch 2, testing avg loss 3.069542, testing avg acc 0.458404\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.542, cost=2.42]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.565, cost=2.46]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.734327, training avg acc 0.497533\n",
      "epoch 3, testing avg loss 2.759604, testing avg acc 0.499930\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.594, cost=2.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.581, cost=2.37]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.377528, training avg acc 0.541794\n",
      "epoch 4, testing avg loss 2.643553, testing avg acc 0.516316\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:47<00:00,  2.41it/s, accuracy=0.634, cost=1.76]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.00it/s, accuracy=0.575, cost=2.32]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.126379, training avg acc 0.575018\n",
      "epoch 5, testing avg loss 2.598078, testing avg acc 0.523783\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.676, cost=1.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.516, cost=2.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.928760, training avg acc 0.602424\n",
      "epoch 6, testing avg loss 2.625970, testing avg acc 0.524454\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.41it/s, accuracy=0.726, cost=1.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  5.00it/s, accuracy=0.565, cost=2.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.765813, training avg acc 0.626288\n",
      "epoch 7, testing avg loss 2.658393, testing avg acc 0.524078\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:44<00:00,  2.42it/s, accuracy=0.737, cost=1.16]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.548, cost=2.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.627493, training avg acc 0.646990\n",
      "epoch 8, testing avg loss 2.707162, testing avg acc 0.522028\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:46<00:00,  2.42it/s, accuracy=0.773, cost=1.01]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.554, cost=2.61]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.502784, training avg acc 0.667045\n",
      "epoch 9, testing avg loss 2.787980, testing avg acc 0.518587\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.788, cost=0.867]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.516, cost=2.74]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.394715, training avg acc 0.684667\n",
      "epoch 10, testing avg loss 2.873492, testing avg acc 0.514365\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.41it/s, accuracy=0.819, cost=0.755]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.538, cost=2.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.296959, training avg acc 0.701351\n",
      "epoch 11, testing avg loss 2.975703, testing avg acc 0.512882\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.832, cost=0.686]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.57, cost=2.91] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.207792, training avg acc 0.716788\n",
      "epoch 12, testing avg loss 3.055867, testing avg acc 0.507040\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.845, cost=0.628]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.05it/s, accuracy=0.548, cost=3.01]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.129608, training avg acc 0.730667\n",
      "epoch 13, testing avg loss 3.144110, testing avg acc 0.504047\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.854, cost=0.574]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.01it/s, accuracy=0.532, cost=3.06]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.059948, training avg acc 0.743214\n",
      "epoch 14, testing avg loss 3.233721, testing avg acc 0.499865\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.851, cost=0.564]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.538, cost=3.15]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.997988, training avg acc 0.754708\n",
      "epoch 15, testing avg loss 3.337412, testing avg acc 0.497933\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.40it/s, accuracy=0.871, cost=0.485]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.532, cost=3.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.940832, training avg acc 0.765438\n",
      "epoch 16, testing avg loss 3.414515, testing avg acc 0.496619\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.879, cost=0.451]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.484, cost=3.39]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.887595, training avg acc 0.775776\n",
      "epoch 17, testing avg loss 3.524169, testing avg acc 0.493390\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:47<00:00,  2.42it/s, accuracy=0.897, cost=0.406]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.00it/s, accuracy=0.505, cost=3.4] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.842631, training avg acc 0.784520\n",
      "epoch 18, testing avg loss 3.598517, testing avg acc 0.492979\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:46<00:00,  2.42it/s, accuracy=0.901, cost=0.385]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.478, cost=3.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.801168, training avg acc 0.792683\n",
      "epoch 19, testing avg loss 3.687797, testing avg acc 0.490220\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:45<00:00,  2.42it/s, accuracy=0.908, cost=0.35] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.16it/s, accuracy=0.495, cost=3.78]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.762615, training avg acc 0.800212\n",
      "epoch 20, testing avg loss 3.755179, testing avg acc 0.488755\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:26<00:00,  1.51it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.17535137"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([943,\n",
       "  2610,\n",
       "  409,\n",
       "  925,\n",
       "  9,\n",
       "  346,\n",
       "  289,\n",
       "  3373,\n",
       "  264,\n",
       "  648,\n",
       "  30773,\n",
       "  391,\n",
       "  9514,\n",
       "  10050,\n",
       "  18603,\n",
       "  445,\n",
       "  289,\n",
       "  1451,\n",
       "  325,\n",
       "  3299,\n",
       "  312,\n",
       "  289,\n",
       "  2196,\n",
       "  317,\n",
       "  1656,\n",
       "  28736,\n",
       "  12770,\n",
       "  1561,\n",
       "  336,\n",
       "  346,\n",
       "  321,\n",
       "  17566,\n",
       "  11387],\n",
       " [648,\n",
       "  671,\n",
       "  409,\n",
       "  3421,\n",
       "  610,\n",
       "  346,\n",
       "  289,\n",
       "  4084,\n",
       "  264,\n",
       "  648,\n",
       "  30773,\n",
       "  3437,\n",
       "  300,\n",
       "  9514,\n",
       "  10050,\n",
       "  18603,\n",
       "  376,\n",
       "  289,\n",
       "  1451,\n",
       "  325,\n",
       "  3299,\n",
       "  312,\n",
       "  289,\n",
       "  2196,\n",
       "  317,\n",
       "  1656,\n",
       "  28736,\n",
       "  26,\n",
       "  1561,\n",
       "  336,\n",
       "  346,\n",
       "  321,\n",
       "  6341,\n",
       "  11387])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rights[0], results[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
